package com.laolang.shop.common.data.mvc.advice;

import com.laolang.shop.common.core.consts.ModuleNameConst;
import com.laolang.shop.common.core.domain.SimpleAjax;
import com.laolang.shop.common.core.exception.BusinessException;
import com.laolang.shop.common.core.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/5 0:21
 */
@Slf4j
@ControllerAdvice
public class MvcExceptionHandle {

    /**
     * 业务报错
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<SimpleAjax<String>> businessHandler(BusinessException e) {
        SimpleAjax<String> ajax = SimpleAjax.failed();
        ajax.setPropFromBusinessException(e);
        LogUtil.error(log, ModuleNameConst.APP, e.getMsg());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ajax);
    }


    /**
     * jsr 303
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<SimpleAjax<Map<String, String>>> jsr303Handler(MethodArgumentNotValidException e) {
        SimpleAjax<Map<String, String>> ajax = SimpleAjax.badRequest();
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            bindingResult.getFieldErrors().forEach(fieldError -> map.put(fieldError.getField(), fieldError.getDefaultMessage()));
            ajax.setBody(map);
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ajax);
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<SimpleAjax<String>> httpRequestMethodNotSupportedException(Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(SimpleAjax.notFount());
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<SimpleAjax<String>> exceptionHandler(Exception e) {
        LogUtil.error(log, ModuleNameConst.APP, e.getMessage());
        SimpleAjax<String> ajax = SimpleAjax.error(e.getMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ajax);
    }
}
